import java.util.*;
import static java.lang.Math.*;

public class TestMathExpr2 {
    private static int pos = -1;
    private static char[] expr;

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("🧮 欢迎使用数学表达式计算器！");
        System.out.println("✨ 支持的运算符：+、-、*、/");
        System.out.println("📐 支持的函数：sin、cos、tan、sqrt");
        System.out.println("⚠️ 请注意：");
        System.out.println("  • 运算符数量不超过5个");
        System.out.println("  • 函数数量不超过3个");
        System.out.println("  • 函数名称中不能有空格");

        System.out.print("📝 请输入要计算的表达式数量 T (1 ≤ T ≤ 20): ");
        int T;
        while (true) {
            try {
                T = Integer.parseInt(scanner.nextLine().trim());
                if (T >= 1 && T <= 20) {
                    break;
                }
                System.out.print("❌ T必须在1到20之间，请重新输入: ");
            } catch (NumberFormatException e) {
                System.out.print("❌ 请输入有效的数字: ");
            }
        }

        System.out.println("\n🎯 请输入" + T + "个数学表达式，每行一个:");

        for (int i = 0; i < T; i++) {
            while (true) {
                try {
                    System.out.print("📌 表达式 #" + (i + 1) + ": ");
                    String expression = scanner.nextLine().trim();

                    // 验证表达式的基本格式
                    if (!isValidExpression(expression)) {
                        System.out.println("❌ 表达式格式无效，请检查后重新输入");
                        continue;
                    }

                    int result = evaluateExpression(expression);
                    System.out.println("✅ 计算结果: " + result);
                    break;

                } catch (Exception e) {
                    System.out.println("❌ 表达式解析错误: " + e.getMessage());
                    System.out.println("请重新输入...");
                }
            }
        }

        System.out.println("\n🎉 计算完成！感谢使用！");
    }

    private static boolean isValidExpression(String expression) {
        if (expression == null || expression.isEmpty()) {
            return false;
        }

        // 检查运算符数量
        int operatorCount = 0;
        for (char c : expression.toCharArray()) {
            if (c == '+' || c == '-' || c == '*' || c == '/') {
                operatorCount++;
            }
        }
        if (operatorCount > 5) {
            System.out.println("❌ 运算符数量不能超过5个");
            return false;
        }

        // 检查函数数量
        int functionCount = 0;
        String[] functions = {"sin", "cos", "tan", "sqrt"};
        for (String func : functions) {
            int index = 0;
            while ((index = expression.indexOf(func, index)) != -1) {
                functionCount++;
                index += func.length();
            }
        }
        if (functionCount > 3) {
            System.out.println("❌ 函数数量不能超过3个");
            return false;
        }

        // 检查括号匹配
        int brackets = 0;
        for (char c : expression.toCharArray()) {
            if (c == '(') brackets++;
            if (c == ')') brackets--;
            if (brackets < 0) {
                System.out.println("❌ 括号不匹配");
                return false;
            }
        }
        if (brackets != 0) {
            System.out.println("❌ 括号不匹配");
            return false;
        }

        return true;
    }

    private static int evaluateExpression(String expression) {
        expr = expression.toCharArray();
        pos = -1;
        double result = parseExpression();
        return (int) Math.round(result);
    }

    private static char nextChar() {
        pos++;
        return pos < expr.length ? expr[pos] : '\0';
    }

    private static void skipWhitespace() {
        while (pos + 1 < expr.length && Character.isWhitespace(expr[pos + 1])) {
            pos++;
        }
    }

    private static double parseExpression() {
        double result = parseTerm();

        while (true) {
            skipWhitespace();
            char ch = nextChar();

            if (ch == '+') {
                result += parseTerm();
            } else if (ch == '-') {
                result -= parseTerm();
            } else {
                pos--;
                break;
            }
        }

        return result;
    }

    private static double parseTerm() {
        double result = parseFactor();

        while (true) {
            skipWhitespace();
            char ch = nextChar();

            if (ch == '*') {
                result *= parseFactor();
            } else if (ch == '/') {
                double divisor = parseFactor();
                if (Math.abs(divisor) < 1e-10) {
                    throw new ArithmeticException("除数不能为零");
                }
                result /= divisor;
            } else {
                pos--;
                break;
            }
        }

        return result;
    }

    private static double parseFactor() {
        skipWhitespace();
        char ch = nextChar();

        if (ch == '(') {
            double result = parseExpression();
            skipWhitespace();
            if (nextChar() != ')') {
                throw new RuntimeException("括号不匹配");
            }
            return result;
        } else if (ch == '-') {
            return -parseFactor();
        } else if (Character.isDigit(ch) || ch == '.') {
            pos--;
            return parseNumber();
        } else if (Character.isLetter(ch)) {
            pos--;
            return parseFunction();
        }

        throw new RuntimeException("无效的表达式格式");
    }

    private static double parseNumber() {
        StringBuilder sb = new StringBuilder();
        char ch;

        // 处理负号
        if (pos + 1 < expr.length && expr[pos + 1] == '-') {
            sb.append('-');
            pos++;
        }

        // 解析数字和小数点
        boolean hasDecimalPoint = false;
        while (pos + 1 < expr.length) {
            ch = expr[pos + 1];
            if (Character.isDigit(ch)) {
                nextChar();
                sb.append(ch);
            } else if (ch == '.' && !hasDecimalPoint) {
                nextChar();
                sb.append(ch);
                hasDecimalPoint = true;
            } else {
                break;
            }
        }

        try {
            return Double.parseDouble(sb.toString());
        } catch (NumberFormatException e) {
            throw new RuntimeException("无效的数字格式: " + sb.toString());
        }
    }

    private static double parseFunction() {
        StringBuilder funcName = new StringBuilder();
        char ch;

        // 解析函数名
        while (pos + 1 < expr.length && Character.isLetter(expr[pos + 1])) {
            ch = nextChar();
            funcName.append(ch);
        }

        skipWhitespace();
        if (nextChar() != '(') {
            throw new RuntimeException("函数缺少左括号");
        }

        double argument = parseExpression();
        skipWhitespace();

        if (nextChar() != ')') {
            throw new RuntimeException("函数缺少右括号");
        }

        String function = funcName.toString();
        switch (function) {
            case "sin":
                return Math.sin(Math.toRadians(argument));
            case "cos":
                return Math.cos(Math.toRadians(argument));
            case "tan":
                return Math.tan(Math.toRadians(argument));
            case "sqrt":
                if (argument < 0) {
                    throw new RuntimeException("sqrt函数的参数不能为负数");
                }
                return Math.sqrt(argument);
            default:
                throw new RuntimeException("未知的函数: " + function);
        }
    }
}